import Taro from "@tarojs/taro";
import {View, Text, ScrollView} from "@tarojs/components";
import "./note-detail.less";
import Util from "../../util/util";
import Api from "../../api/api";
import dayjs from "dayjs";
import {AtButton, AtRadio, AtFloatLayout, AtFab, AtNavBar} from "taro-ui";
import {isLogin, checkLogin, getGlobal} from "../../api/globalData";
import addImg from "../../assets/image/add.png";
import NavBar from "../../commponents/nav-bar/nav-bar"

export default class NoteDetail extends Taro.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      noteId: "",
      html: "",
      author: "",
      time: "",
      showPopup: false,
      subjectList: [],
      selectSubjectId: null,
      from: 0,// 从哪里跳过来的 0.文章列表页 1.我的收藏页, 2.搜索页
      pageHeight: getGlobal("screenHeight") - 300,
    };
  }

  config = {
    navigationBarTitleText: "",
    usingComponents: {
      "we-mark": "../../plugins/wemark/wemark",
    },
  };

  componentDidShow() {
    this.getSubjectList(this.noteId);
  }

  componentWillMount() {
    const param = this.$router.params;
    this.setState({
      noteId: param.noteId,
      from: param.from ? Number(param.from) : 0
    });
  }

  // 分享出去的入口
  onShareAppMessage(res) {
    return {
      title: this.state.title
    }
  }

  async componentDidMount() {
    this.getDetail(this.state.noteId);
  }

  async getDetail(id) {
    if (!id) {
      id = "segment-/a/1190000018935873";
    }

    let d = await Api.docDetail(id);
    let res = d.data.data;
    let markdown = res.markdown;
    this.setState({
      html: markdown,
      author: res.author,
      time: Util.timeAgo(dayjs(res.createdAt).valueOf()),
      title: res.title,
      // enterCache: !!weMark
    });
  }

  toCreateCollect() {
    if (!checkLogin()) {
      return;
    }

    Taro.navigateTo({
      url: `/pages/create-collect/create-collect`
    });
  }

  async getSubjectList(id) {
    if (!isLogin()) {
      return;
    }

    if (!id) {
      id = "segment-/a/1190000018505993";
    }
    let res = await Api.personSubject(id, 1);
    let data = res.data;
    if (data.success) {
      const list = data.data.list;
      if (list.length > 0) {
        this.setState({
          subjectList: list,
          selectSubjectId: String(list[0].id)
        });
      }
    }
  }

  async addNoteToSubject() {
    if (!checkLogin()) {
      return;
    }
    let operate = {
      noteId: this.state.noteId,
      opType: 1,
      noteType: 1,
      subjectId: this.state.selectSubjectId
    };
    let res = await Api.operateSubjetNote(operate);
    if (res.data.success) {
      this.closeActionSheet();
      Taro.showToast({title: "添加成功"});
    }
  }

  starDoc() {
    if (!checkLogin()) {
      return;
    }
    this.setState({showPopup: true});
    this.getSubjectList(this.state.noteId);
  }

  closeActionSheet() {
    this.setState({showPopup: false});
  }

  changeSubject(item) {
    this.setState({selectSubjectId: item});
  }

  render() {
    let arr = [];
    if (this.state.subjectList.length > 0) {
      this.state.subjectList.map(v => {
        let obj = {};
        obj.value = String(v.id);
        obj.label = v.name;
        obj.desc = `文章数:${v.postNum}
            ${v.inSubject ? "| 已加入" : ""}`;
        arr.push(obj);
      });
    }
    const isLog = isLogin();

    let actionBody = (
      <View className="collect-content">
        <View className="create-collect">
          <View
            className="create-btn flex-align-items-center"
            onTap={this.toCreateCollect.bind(this)}
          >
            <Image src={addImg}/>
            <Text>新建收藏夹</Text>
          </View>
        </View>
        <ScrollView className="radio-list" scroll-y style={{height: "260PX"}}>
          <AtRadio
            value={this.state.selectSubjectId}
            options={arr}
            onClick={this.changeSubject.bind(this)}
          />
        </ScrollView>
        <View className="padding-10 create-bottom-btn" style="padding:10PX;">
          <Button
            type="primary"
            onTap={this.addNoteToSubject.bind(this)}
            style="height: 38PX;line-height: 38PX;"
            disabled={this.state.selectSubjectId === null}
          >
            添加
          </Button>
        </View>
      </View>
    );

    return (
      <View>
        <NavBar title="微Coding" showSearch={this.state.from === 0}/>
        <View style={{
          height: `${this.state.showPopup ? this.state.pageHeight + 'px' : '100%'}`,
          overflowY: `${this.state.showPopup ? 'hidden' : 'auto'}`,
          marginTop: `${getGlobal("navBarHeight") + 44}px}`
        }}>
          {this.state.html !== "" ? <View>
            <View className="m-content">
              <View className="m-wrapper">
                <View className="m-doc-article">
                  <article id="content" className="article-content">
                    <View className="doc-content">
                      <View className="lake-engine-view">
                        <View className="top card">
                          <View className="title___3ntsK">
                            <Text id="article-title" className="article-title">{this.state.title}</Text>
                          </View>
                          <View className="meta___2e9i0">
                          <span className="metaContributors___EyryE">
                            <span>{this.state.author}</span>
                          </span>
                            <span style="padding:0 5PX">·</span>
                            <span className="metaTime___3qSx7">
                            <span>{this.state.time}</span>
                          </span>
                          </View>
                        </View>
                        <View className="bottom card">
                          <we-mark md={html} link highlight type="wemark"/>
                        </View>
                      </View>
                    </View>
                  </article>
                </View>
              </View>
            </View>
            <View>
              {this.state.from != 1 && isLog ? (
                <View className="starDoc">
                  <View className="float-btn" onTap={this.starDoc.bind(this)}>
                    <AtFab size='small'>
                      <Text className="at-fab__icon at-icon at-icon-star"/>
                    </AtFab>
                  </View>
                  <View className="float-btn">
                    <AtFab size='small'>
                      <AtButton className='at-fab__icon at-icon at-icon-share' size='small' openType="share"/>
                    </AtFab>
                  </View>
                </View>
              ) : (
                ""
              )}
            </View>
            <AtFloatLayout
              isOpened={this.state.showPopup}
              title="收藏夹"
              onClose={this.closeActionSheet.bind(this)}
            >
              {actionBody}
            </AtFloatLayout></View> : ""}
        </View>
      </View>

    );
  }
}
